﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.MobileGPS;
using Microsoft.WindowsMobile.PocketOutlook.MessageInterception;
using Microsoft.WindowsMobile.PocketOutlook;
using System.Diagnostics;

namespace SMSCoordinate
{
    public partial class AutoSMS : Form
    {
        private SMSManager smsManager = null;
        
        private static string TEXT_ACCEPTED = "were are you";

        private static string LONLAT_TEXT_FORMAT = @"Hi, I am at here : http://maps.google.com/maps?q={0},{1}";

        public AutoSMS()
        {
            InitializeComponent();
        }
        
        private void Form1_Activated(object sender, EventArgs e)
        {
            this.Hide();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            MessageCondition condition = new MessageCondition();
            condition.Property = MessageProperty.Body;
            condition.ComparisonType = MessagePropertyComparisonType.Equal;
            condition.CaseSensitive = true;
            condition.ComparisonValue = TEXT_ACCEPTED;

            smsManager = new SMSManager(new MessageInterceptorEventHandler(OnMessageReceiver), condition);
                    
        }

        private void OnMessageReceiver(object sender, MessageInterceptorEventArgs e)
        {
            SmsMessage message = (SmsMessage) e.Message;
            if (message.Body.CompareTo(TEXT_ACCEPTED) == 0)
            {
                string fromNumber = message.From.Address;
                Coordinate coordinate = new Coordinate();
                try
                {
                    Gps gps = new Gps();
                    gps.Open();
                    GpsPosition position = gps.GetPosition();


                    if (position.LatitudeValid)
                    {
                        coordinate.Latitude = position.Latitude;
                    }
                    if (position.LongitudeValid)
                    {
                        coordinate.Longitude = position.Longitude;
                    }
                }
                catch (Exception ex)
                {

                }
                string str = String.Format(LONLAT_TEXT_FORMAT, coordinate.Latitude, coordinate.Longitude);
                SMSManager.SendSMS(fromNumber, str);
            }
        }
    }
}